// Module: fv_calc (with packed arrays)
// Description: Calculate the Fair Value (FV) with respect to the main instrument.
//              Stores the calculated result of every instrument in fv_all[].

module fv_calc #(
    parameter int NUM_CONTRACTS = 3
)(
    input logic clk_net,
    input logic rst_n,

    input logic [31:0] royal_gala_bidprice,
    input logic [31:0] royal_gala_askprice,
    input logic [7:0]  royal_gala_bidvolume,
    input logic [7:0]  royal_gala_askvolume,

    input logic [NUM_CONTRACTS-1:0][31:0] rels,   // packed

    input logic fv_recalc_trigger,

    output logic [NUM_CONTRACTS-1:0][31:0] fv_all  // packed
);

    // Pipelining
    logic [39:0] mult1, mult2;      // Store the results of two multiplications
    logic [40:0] sum;               // Store the sum of two products
    logic [8:0]  denom;             // Store the calculated demoniantor
    logic [31:0] royal_gala_fv;     // Final result of the calculation

    integer j;
    always_ff @(posedge clk_net) begin
        if (!rst_n) begin
            mult1 <= 0;
            mult2 <= 0;
            sum <= 0;
            denom <= 1;
            royal_gala_fv <= 0;
            for (j = 0; j < NUM_CONTRACTS; j++) begin
                fv_all[j] <= 0;
            end
        end else begin
            if (fv_recalc_trigger) begin
            // FV for Royal Gala
                mult1 <= royal_gala_bidprice * royal_gala_askvolume;
                mult2 <= royal_gala_askprice * royal_gala_bidvolume;
                denom <= royal_gala_bidvolume + royal_gala_askvolume;
            end

            sum <= mult1 + mult2;

            if (denom != 0) royal_gala_fv <= sum / denom;
            else royal_gala_fv <= 0;

            // Update all apple types based on the FV of Royal Gala
            for (j = 0; j < NUM_CONTRACTS; j++) begin
                fv_all[j] <= royal_gala_fv + rels[j]; 
            end
        end
    end

endmodule
